var cheerio = require("cheerio");
var request = require("request");
var iconv = require("iconv-lite");

var isAbsoluteUri = function(href) {
	return (href.indexOf("http://") == 0 || href.indexOf("https://") == 0 || href.indexOf("//") == 0);
}

var emptyBody = function(body) {
    for (var i in body) {
        return false;
    }
    return true;
}

exports.proxy = function(req, res) {
	var origUri = req.originalUrl.replace("/proxypath/", "");
	var path = req.path.replace("/proxypath/", "");
	var serverPath = path.split('/').slice(0, 3).join('/');

	var data = { 
		method: req.method, 
		uri: origUri, 
		followAllRedirects: true, 
		encoding: "binary" 
	};

	if (!emptyBody(req.body)) {
		data.form = req.body;
		console.log(data);
	}

	request(data, function(error, response, body) {
		if (!error && parseInt(response.statusCode / 100) == 2) {
			var headers = response.headers["content-type"].split('=');
			if (headers[0].indexOf("text/html") == 0) {
				var $ = cheerio.load(body);
				var encoding;
				if (headers.length > 1)
					encoding = headers[headers.length - 1];
				else {
					try {
						var header = $('meta[content*="charset"]').attr("content").split('=');
						encoding = header[header.length - 1];
					} catch (exception) {
						try {
							encoding = $('meta[charset]').attr("charset");
						} catch (ex) {
							encoding = "utf-8";
						}
					}
				}
				$ = cheerio.load(iconv.decode(body, encoding));

				$('a[href]').each(function(index) {
					var href = $(this).attr("href");
					if (href) {
						if (href && !isAbsoluteUri(href)) {
							href = path + "/" + href;
						} 
						$(this).attr("href", "/proxypath/" + href);
					}
				});

				$('link[href]').each(function(index) {
					var href = $(this).attr("href");
					if (href) {
						if (href && !isAbsoluteUri(href)) {
							if (href[0] == '/')
								href = serverPath + href;
							else
								href = path + "/" + href;
						} 
						$(this).attr("href", href);
					}
				});

				$('[src]').each(function(index) {
					var href = $(this).attr("src");
					if (href) {
						if (href && !isAbsoluteUri(href)) {
							if (href[0] == '/')
								href = serverPath + href;
							else
								href = path + "/" + href;
						} 
						$(this).attr("src", href);
					}
				});

				$('[action]').each(function(index) {
					var href = $(this).attr("action");
					if (href) {
						if (href && !isAbsoluteUri(href)) {
							href = path + "/" + href;
						} 
						$(this).attr("action", "/proxypath/" + href);
					}
				});

				if ($('base').length == 0) {
					$('head').append("<base />");
				}
				$('base').attr('href', "/proxypath/" + serverPath);

				res.end($.html());
			} else {
				res.end(body);
			}
		} else {
			res.statusCode = response.statusCode;
			res.end(error);
		}
	});
}